package bill.study.concurrency.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

class CacheData {
	Object data;
	volatile boolean cacheValid;
	ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

	void processCachedData() {
	     readWriteLock.readLock().lock();
	     if (!cacheValid) {
	        // upgrade lock manually
	        readWriteLock.readLock().unlock();   // must unlock first to obtain writelock
	        readWriteLock.writeLock().lock();
	        if (!cacheValid) { // recheck
	          data =  null;//...
	          cacheValid = true;
	        }
	        // downgrade lock
	        readWriteLock.readLock().lock();  // reacquire read without giving up write lock
	        readWriteLock.writeLock().unlock(); // unlock write, still hold read
	     }

	     use(data);
	     readWriteLock.readLock().unlock();
	   }

	private void use(Object data2) {
		// TODO Auto-generated method stub
		
	}
}
